package com.lizicloud.user.userinfo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lizicloud.application.dto.ApiResponse;
import com.lizicloud.domain.model.User;
import com.lizicloud.infrastructure.persistence.UserMapper;
import com.lizicloud.user.userinfo.dto.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息管理服务类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserInfoService {
    
    private final UserMapper userMapper;
    
    /**
     * 获取用户信息
     */
    public ApiResponse<UserInfoDTO> getUserInfo(Long userId) {
        try {
            User user = userMapper.selectById(userId);
            if (user == null) {
                return ApiResponse.error("用户不存在");
            }
            
            UserInfoDTO userInfoDTO = convertToUserInfoDTO(user);
            return ApiResponse.success(userInfoDTO);
            
        } catch (Exception e) {
            log.error("获取用户信息失败，用户ID: {}", userId, e);
            return ApiResponse.error("获取用户信息失败");
        }
    }
    
    /**
     * 更新用户信息
     */
    @Transactional
    public ApiResponse<UserInfoDTO> updateUserInfo(UpdateUserDTO updateUserDTO) {
        try {
            log.info("更新用户信息，用户ID: {}, 更新内容: {}", updateUserDTO.getId(), updateUserDTO);
            
            User user = userMapper.selectById(updateUserDTO.getId());
            if (user == null) {
                return ApiResponse.error("用户不存在");
            }
            
            // 更新基本用户信息
            user.setUsername(updateUserDTO.getUsername());
            // 处理空字符串邮箱问题 - 空字符串转换为null避免UNIQUE约束冲突
            String email = updateUserDTO.getEmail();
            user.setEmail((email != null && email.trim().isEmpty()) ? null : email);
            user.setPhone(updateUserDTO.getPhone());
            user.setAvatar(updateUserDTO.getAvatar());
            user.setRemark(updateUserDTO.getRemark());
            
            // 更新角色和状态（如果提供）
            if (updateUserDTO.getRole() != null) {
                user.setRole(updateUserDTO.getRole());
            }
            if (updateUserDTO.getStatus() != null) {
                user.setStatus(updateUserDTO.getStatus());
            }
            
            user.setUpdatedTime(LocalDateTime.now());
            
            int updateCount = userMapper.updateById(user);
            if (updateCount == 0) {
                return ApiResponse.error("更新用户信息失败");
            }
            
            log.info("用户更新成功，用户ID: {}", updateUserDTO.getId());
            
            UserInfoDTO userInfoDTO = convertToUserInfoDTO(user);
            return ApiResponse.success(userInfoDTO);
            
        } catch (Exception e) {
            log.error("更新用户信息失败，用户ID: {}", updateUserDTO.getId(), e);
            return ApiResponse.error("更新用户信息失败");
        }
    }
    
    /**
     * 更新用户状态
     */
    @Transactional
    public ApiResponse<Void> updateUserStatus(UpdateUserStatusDTO updateUserStatusDTO) {
        try {
            User user = userMapper.selectById(updateUserStatusDTO.getId());
            if (user == null) {
                return ApiResponse.error("用户不存在");
            }
            
            user.setStatus(updateUserStatusDTO.getStatus());
            user.setUpdatedTime(LocalDateTime.now());
            
            userMapper.updateById(user);
            
            log.info("更新用户状态成功，用户ID: {}，状态: {}", 
                    updateUserStatusDTO.getId(), updateUserStatusDTO.getStatus());
            return ApiResponse.success(null);
            
        } catch (Exception e) {
            log.error("更新用户状态失败，用户ID: {}", updateUserStatusDTO.getId(), e);
            return ApiResponse.error("更新用户状态失败");
        }
    }
    
    /**
     * 获取用户列表（管理员功能）
     */
    public ApiResponse<UserListResponseDTO> getUserList(UserListQueryDTO queryDTO) {
        try {
            // 构建查询条件
            com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            
            if (queryDTO.getUsername() != null && !queryDTO.getUsername().trim().isEmpty()) {
                queryWrapper.like("username", queryDTO.getUsername().trim());
            }
            
            if (queryDTO.getUseraccount() != null && !queryDTO.getUseraccount().trim().isEmpty()) {
                queryWrapper.like("useraccount", queryDTO.getUseraccount().trim());
            }
            
            if (queryDTO.getRole() != null && !queryDTO.getRole().trim().isEmpty()) {
                queryWrapper.eq("role", queryDTO.getRole().trim());
            }
            
            if (queryDTO.getStatus() != null) {
                queryWrapper.eq("status", queryDTO.getStatus());
            }
            
            // 按创建时间倒序排序
            queryWrapper.orderByDesc("created_time");
            
            // 创建分页对象
            Page<User> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
            
            // 执行分页查询
            IPage<User> userPage = userMapper.selectPage(page, queryWrapper);
            
            // 转换数据
            java.util.List<UserListItemDTO> userList = userPage.getRecords().stream()
                    .map(this::convertToUserListItemDTO)
                    .collect(java.util.stream.Collectors.toList());
            
            UserListResponseDTO response = new UserListResponseDTO();
            response.setRecords(userList);
            response.setTotal(userPage.getTotal());
            response.setPageNum(queryDTO.getPageNum());
            response.setPageSize(queryDTO.getPageSize());
            
            return ApiResponse.success(response);
            
        } catch (Exception e) {
            log.error("获取用户列表失败", e);
            return ApiResponse.error("获取用户列表失败");
        }
    }

    /**
     * 获取用户统计信息：总数、管理员数、普通用户数、已删除用户数
     */
    public ApiResponse<UserStatsDTO> getUserStats() {
        try {
            long total = userMapper.countActiveUsers();
            long admins = userMapper.countActiveAdmins();
            long normals = userMapper.countActiveNormalUsers();
            long deleted = userMapper.countDeletedUsers();
            UserStatsDTO stats = new UserStatsDTO(total, admins, normals, deleted);
            return ApiResponse.success(stats);
        } catch (Exception e) {
            log.error("获取用户统计失败", e);
            return ApiResponse.error("获取用户统计失败");
        }
    }
    
    /**
     * 将User实体转换为UserInfoDTO
     */
    private UserInfoDTO convertToUserInfoDTO(User user) {
        UserInfoDTO dto = new UserInfoDTO();
        dto.setId(user.getId());
        dto.setUseraccount(user.getUseraccount());
        dto.setUsername(user.getUsername());
        dto.setRole(user.getRole());
        dto.setEmail(user.getEmail());
        dto.setPhone(user.getPhone());
        dto.setAvatar(user.getAvatar());
        dto.setStatus(user.getStatus());
        dto.setLastLoginTime(user.getLastLoginTime());
        dto.setLastLoginIp(user.getLastLoginIp());
        dto.setCreatedTime(user.getCreatedTime());
        dto.setUpdatedTime(user.getUpdatedTime());
        return dto;
    }
    
    /**
     * 将User实体转换为UserListItemDTO
     */
    private UserListItemDTO convertToUserListItemDTO(User user) {
        UserListItemDTO dto = new UserListItemDTO();
        dto.setId(user.getId());
        dto.setUseraccount(user.getUseraccount());
        dto.setUsername(user.getUsername());
        dto.setRole(user.getRole());
        dto.setEmail(user.getEmail());
        dto.setPhone(user.getPhone());
        dto.setStatus(user.getStatus());
        dto.setLastLoginTime(user.getLastLoginTime());
        dto.setLastLoginIp(user.getLastLoginIp());
        dto.setCreatedTime(user.getCreatedTime());
        dto.setUpdatedTime(user.getUpdatedTime());
        return dto;
    }
}